import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { PassportStrategy } from '@nestjs/passport'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { ConfigEnum } from '@/enum/config.enum'

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(protected configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get(`${ConfigEnum.JWT_CONFIG}.secret`),
    })
  }

  async validate(payload: any): Promise<PayloadUserType> {
    // return payload
    const roles = payload.roles.map((userRole) => userRole.role.roleCode)
    const buttons = payload.roles
      .map((userRole) => userRole.role.permissions.map((permission) => permission.permissionCode))
      .flat()
    return {
      userId: payload.id,
      userName: payload.userName,
      roles,
      buttons,
    }
  }
}
